package cn.dlc.com.interceptor;

import cn.dlc.com.user.model.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 邓立川
 * @date 2021/11/21 11:42
 * @desc 当前类的描述信息
 */
public class MyAuthenticateInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("request.getRequestURI(): " + request.getRequestURI());

        // 校验身份
        Object user_ = request.getSession().getAttribute("user_");
        if(user_ == null) {
            writeContent(response,"请登录");
            return false;
        }

        System.out.println("interceptor..............");

        User user = (User) user_;
        // p1可以反问r1，p2可以访问r2.
        if(user.getAuthenticateList().contains("p1") && request.getRequestURI().contains("/r1")) {
            // 有权限
            return true;
        }
        if(user.getAuthenticateList().contains("p2") && request.getRequestURI().contains("/r2")) {
            // 有权限
            return true;
        }
        writeContent(response,"没有权限");

        return false;
    }

    private void writeContent(HttpServletResponse response, String msg) throws Exception{
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(msg);
        writer.flush();
        writer.close();
        response.resetBuffer();
    }
}
